﻿using BasicData.Domain;
using BasicData.ErrorCode;
using BasicData.Infastruucture;
using BasicData.Read.API.application.Command.User;
using BasicData.Read.API.DTO;
using MediatR;

namespace BasicData.Read.API.application.CommandHandler.User
{
    public class UserCommandHandler : IRequestHandler<UserCommand, ApiResult<UserDTO>>
    {
        private readonly IBaseRepository<UserModel> userRep;
        private readonly IBaseRepository<RoleModel> roleRep;
        private readonly IBaseRepository<UserRoleModel> userroleRep;

        public UserCommandHandler(IBaseRepository<UserModel> UserRep,IBaseRepository<RoleModel> RoleRep,IBaseRepository<UserRoleModel> userroleRep)
        {
            this.userRep = UserRep;
            this. roleRep = RoleRep;
            this.userroleRep = userroleRep;
        }
        public Task<ApiResult<UserDTO>> Handle(UserCommand request, CancellationToken cancellationToken)
        {
           ApiResult<UserDTO> result = new ApiResult<UserDTO>();
            var user=userRep.GetAll().Where(x=>x.UserName == request.UserName).FirstOrDefault();
            if(user==null)
            {
                result.Code = BaseEnums.Failed;
                result.Msg = "用户名不存在";
                result.Data = null;
                return Task.FromResult(result);
            }
            else
            {
                if(user.Password!=request.Password)
                {
                    result.Code = BaseEnums.Failed;
                    result.Msg = "密码错误";
                    result.Data = null;
                    return Task.FromResult(result);
                }
                else
                {
                    result.Code = BaseEnums.Success;
                    result.Msg = "登录成功";
                    var userrole=userroleRep.GetAll().Where(x=>x.UserId==user.UserId).FirstOrDefault();
                    var role=roleRep.GetAll().Where(x=>x.RoleId==userrole.RoleId).FirstOrDefault();
                    UserDTO userDTO = new UserDTO()
                    {
                         Password=user.Password,
                          UserName=user.UserName,
                           Phone=user.Phone,
                            RoleName=role.RoleName,
                             Status=user.Status,
                              UserId=user.UserId,
                               UserNickName=user.UserNickName
                    };
                    result.Data = userDTO;
                   
                    return Task.FromResult(result);
                }
            }
        }
    }
}
